﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;

namespace Cmpp.Client {
    internal class SocketAsyncEventArgsPool {
        private readonly Stack<SocketAsyncEventArgs> m_pool;
        private readonly object syncLocker = new object();

        public SocketAsyncEventArgsPool(int capacity) {
            m_pool = new Stack<SocketAsyncEventArgs>(capacity);
        }

        public void Push(SocketAsyncEventArgs item) {
            if (item == null) { throw new ArgumentNullException("item"); }
            lock (syncLocker) {
                if (item.AcceptSocket != null) {
                    item.AcceptSocket = null;
                }
                m_pool.Push(item);
            }
        }

        public SocketAsyncEventArgs Pop() {
            lock (syncLocker) {
                if (Count == 0) {
                    return null;
                }

                return m_pool.Pop();
            }
        }

        public int Count {
            get { return m_pool.Count; }
        }
    }
}
